import { useEffect, useState } from 'react';
import { Button, Space, Form, Row, Col, Input, Table, Modal, Descriptions, Tag, Select, QRCode, Flex } from 'antd';
import usePageAccess from '@/components/usePageAccess';
import { Access, history } from '@umijs/max'
import { PAGINATION_CONFIG } from '@/constants';
import type { QueryEquipmentListParams, Stub } from '../stubList/services';
import { EquipmentType, GunStatus, GunStatusColorMap, queryStubList, StubType } from '../stubList/services'
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import StubEditModal, { StubEditModalProps } from './components/StubEditModal';
import StationSelect from '@/components/StationSelect';
import { enum2options } from '@/utils/enum2options';
import { jump2target } from '@/utils/common';
import dayjs from 'dayjs';
import { CheckCircleFilled } from '@ant-design/icons';
import { exportStation, exportStub } from '@/pages/order/chargeOrder/services';
import OrgSelect from '@/components/OrgSelect';

function doDownload(url: string, fileName: string) {
  const a = document.createElement('a');
  a.download = fileName;
  a.href = url;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

const downloadCanvasQRCode = (fileName: string) => {
  const canvas = document.getElementById('stubQRCode')?.querySelector<HTMLCanvasElement>('canvas');
  if (canvas) {
    const url = canvas.toDataURL();
    doDownload(url, fileName);
  }
}

let stubId = ''

const EquipmentPage: React.FC<RoutePageProps> = (props) => {
  const access = usePageAccess()
  const [searchForm] = Form.useForm<any>()
  const expReq = useRequest(exportStub, {manual: true})
  const [searchParams, setSearchParams] = useState<QueryEquipmentListParams>({
    pageNum: 1, pageSize: 10,
  })
  const stubList = useRequest(() => queryStubList(searchParams), {
    refreshDeps: [searchParams],
  })
  const [stubEditModalProps, setStubEditModalProps] = useState<StubEditModalProps>({
    open: false, type: 'look'
  })
  const [detailRecord, setDetailRecord] = useState<Stub>()
  const [qrCode, setQrCode] = useState<string>()

  const onFinish = (formValues: any) => {
    setSearchParams({
      ...searchParams,
      stationTitle: formValues.station?.[0]?.name,
      stubType: formValues.stubType,
      equipmentId: formValues.equipmentId,
      stubName: formValues.stubName,
      status: formValues.status,
      orgId: formValues.org?.id,
      pageNum: 1,
    })
  }
  
  const onStubModalCancel = (refresh?: boolean) => {
    if (refresh) stubList.refresh()
    setStubEditModalProps({open: false, type: 'look'})
  }

  const openEditModal = (title: string, type: 'edit' | 'look', record?: Stub) => {
    setStubEditModalProps({
      type, open: true, title,
      stub: record
    })
  }

  const lookLog = (record: Stub) => {
    jump2target(`/station/stubLog?stubId=${record.id}`, {needRefresh: true})
  }

  const openDetailModal = (record: Stub) => {
    setDetailRecord(record)
  }

  const closeQRCodeModal = () => {
    stubId = ''
    setQrCode(undefined)
  }

  const exportExcel = () => {
    const formValues = searchForm.getFieldsValue()
    const _params = {
      ...searchParams,
      stationTitle: formValues.station?.[0]?.name,
      stubType: formValues.stubType,
      equipmentId: formValues.equipmentId,
      stubName: formValues.stubName,
      orgId: formValues.org?.id,
      status: formValues.status,
    }
    expReq.runAsync(_params)
      .then(res => {
        Modal.confirm({
          icon: <CheckCircleFilled style={{color: 'red'}} />,
          content: '导出申请成功，请前往导出记录查看文档。',
          onOk: () => {
            jump2target('/report/exportUrl')
          }
        })
      })
  }

  const openQRCodeModal = (record: Stub) => {
    stubId = record.id
    setQrCode(record.scanCode)
  }

  const downloadQRCode = () => {
    downloadCanvasQRCode(stubId)
    closeQRCodeModal()
  }

  const columns: ColumnsType<Stub> = [
    {
      title: '枪编号',
      dataIndex: 'id',
      width: 120,
    },
    {
      title: '设备编号',
      dataIndex: 'equipmentId',
      width: 120,
    },
    {
      title: '场站名称',
      dataIndex: 'stationName',
    },
    {
      title: '所属经销商',
      dataIndex: 'orgName',
    },
    {
      title: '电流(A)',
      dataIndex: 'current',
      width: 140,
    },
    {
      title: '最大功率(kw)',
      dataIndex: 'kw',
      width: 140,
    },
    {
      title: '枪状态',
      dataIndex: 'status',
      width: 120,
      render: val => {
        switch (val) {
          case GunStatus.充电中: return <Tag color={GunStatusColorMap[GunStatus.充电中]}>充电中</Tag>
          case GunStatus.充电后占位: return <Tag color={GunStatusColorMap[GunStatus.充电后占位]}>充电后占位</Tag>
          case GunStatus.故障: return <Tag color={GunStatusColorMap[GunStatus.故障]}>故障</Tag>
          case GunStatus.离线: return <Tag color={GunStatusColorMap[GunStatus.离线]}>离线</Tag>
          case GunStatus.空闲: return <Tag color={GunStatusColorMap[GunStatus.空闲]}>空闲</Tag>
          case GunStatus.插枪空闲: return <Tag color={GunStatusColorMap[GunStatus.插枪空闲]}>插枪空闲</Tag>
          case GunStatus.其他: 
          default: return <Tag color={GunStatusColorMap[GunStatus.其他]}>其他</Tag>
        }
      }
    },
    {
      title: '枪标准',
      dataIndex: 'standardType',
      width: 140,
      render: val => val ? StubType[val] : '--'
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      width: 140,
      render: val => val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : ''
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 240,
      render: (id: number, record) => {
        return <Space>
          <Access accessible={!!record.scanCode}>
            <a onClick={() => openQRCodeModal(record)}>查看二维码</a>
          </Access>
          <a onClick={() => lookLog(record)}>查看日志</a>
          <a onClick={() => openDetailModal(record)}>详情</a>
          <Access accessible={!record.operationId}>
            <a onClick={() => openEditModal('编辑枪信息', 'edit', record)}>编辑</a>
          </Access>
        </Space>
      }
    }
  ]

  useEffect(() => {
    const { equipmentId } = props.params
    if (equipmentId) {
      searchForm.setFieldsValue({equipmentId})
      onFinish({equipmentId})
    }
  }, [props.params.equipmentId])

  useEffect(() => {
    const refresh = () => {
      stubList.refresh()
    }
    window.addEventListener('refreshStubList', refresh)
    return () => {
      window.removeEventListener('refreshStubList', refresh)
    }
  }, [])
  
  return (
    <div className='container'>
      <div className="card search-card">
        <Access accessible={!!access.add || true}>
          <div className="toolbar">
            <Space>
              <Button type='primary' onClick={() => openEditModal('添加枪信息', 'edit')}>添加枪信息</Button>
            </Space>
          </div>
        </Access>
        <div className="form-area">
          <Form name='searchStubForm' form={searchForm} onFinish={onFinish}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='电站名称' name='station'>
                  <StationSelect allowClear inline />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='设备类型' name='stubType'>
                  <Select placeholder='请选择' options={enum2options(EquipmentType)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='设备编号' name='equipmentId'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='经销商ID' name='org'>
                  <OrgSelect allowClear inline />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={stubList.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                  <Button onClick={exportExcel} loading={expReq.loading}>导出</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<Stub>
          rowKey='id'
          loading={stubList.loading}
          dataSource={stubList.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: stubList.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
      <StubEditModal
        {...stubEditModalProps}
        onCancel={onStubModalCancel}
      />
      <Modal
        title='枪信息'
        open={!!detailRecord}
        footer={false}
        onCancel={() => setDetailRecord(undefined)}
      >
        <Descriptions column={1}>
          <Descriptions.Item label='枪编号'>{detailRecord?.id}</Descriptions.Item>
          <Descriptions.Item label='枪名称'>{detailRecord?.name}</Descriptions.Item>
          <Descriptions.Item label='最大功率(kW)'>{detailRecord?.kw}</Descriptions.Item>
          <Descriptions.Item label='额定电压下限(V)'>{detailRecord?.voltageBegin}</Descriptions.Item>
          <Descriptions.Item label='额定电压上限(V)'>{detailRecord?.voltageEnd}</Descriptions.Item>
          <Descriptions.Item label='枪标准'>{detailRecord?.standardType ? StubType[detailRecord.standardType] : '--'}</Descriptions.Item>
        </Descriptions>
      </Modal>
      <Modal
        title='二维码'
        open={!!qrCode}
        onCancel={() => setQrCode(undefined)}
        footer={[
          <Button key='cancel' onClick={closeQRCodeModal}>关闭</Button>,
          <Button key='download' type='primary' onClick={downloadQRCode}>下载</Button>,
        ]}
      >
        <Flex id='stubQRCode' align='center' justify='center'>
          <Access accessible={!!qrCode}>
            <QRCode value={qrCode!} />
          </Access>
        </Flex>
      </Modal>
    </div>
  );
};

export default EquipmentPage;
